# encoding=utf-8
'''
Created on 2012-12-30

@author: Administrator
'''
from actionModule.handle import base
from base.common import retSuccess, toDict
from base.dbCommon import convertToArray
from config.db.models import moduleTable, Field
from config.settings import PROJECT_PATH
from django.forms.models import model_to_dict
import json


formJson = [
          {'id':'id', 'key':'Hidden', 'name':'主键'},
          {'id':'name', 'key':'Input', 'name':'模板名称', 'noNull':True},
          {'id':'fieldType', 'key':'Select', 'name':'模板类型', 'noNull':True,'subs':[{"id":"form","text":"字段"},{"id":"other","text":"模板"}]},
          {'id':'jsonKey', 'key':'Input', 'name':'模板键值', 'noNull':True},
          {'id':'code', 'key':'Field', 'name':'编码', 'noNull':True},
          {'id':'version', 'key':'Input', 'name':'版本号', 'noNull':True},
          {'id':'content', 'key':'TextArea', 'name':'内容','detail_key':'TextArea'},
          {'key':'Submit', 'action':'template.create','relaTable':'templateTable','back':'closeTab'},
         ]

filePath=PROJECT_PATH+"/yqy/html/templates/common/"

class template(base):
    
    def __init__(self):
        self.formJson=formJson  
    
    def create(self):
        
        item = moduleTable()
        for temp in self.request.params:
            item.setAttr(temp, self.request.params.get(temp))
            
        if not item['version']:
            item.setAttr('version','1.0')
            
        fileName=item.jsonKey+(item.version if item.version else '1.0')+".html"
        path=filePath+fileName
        uploadFile=open(path,"wb")
        uploadFile.write(item.content)
        uploadFile.close()
        #数据库中不保存模板内容
        item.setAttr('content','')
        item.save()
        return toDict(item)

    def queryAll(self):
        return convertToArray(moduleTable.objects.filter(fieldType='form').values())    
    
    def saveField(self):
        item = Field()
        for temp in self.request.params:
            item.setAttr(temp, self.request.params.get(temp))
        item.save()
        return model_to_dict(item)
    def queryField(self):
        key=self.request.POST.get("key")
        return convertToArray(Field.objects.filter(field=key).values())
        
    def delField(self):
        items=self.request.POST.items()
        param=json.loads(items[0][0]) 
        fields=param['fields']
        for temp in fields:
            Field.objects.filter(id=temp).delete()
        
        return retSuccess("删除成功")
        
    def getById(self):
        retBean = self.table.objects.get(id=self.getPost("id"))
        dictBean=toDict(retBean)
        tempFile=open(filePath+"/"+dictBean['jsonKey']+dictBean['version']+".html","rb")
        dictBean['content']=tempFile.read()
        return dictBean
        